import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import {Message} from 'element-ui'
//基准路径

//要用instance
var instance = axios.create({
	baseURL: "http://127.0.0.1"
})

//请求拦截
instance.interceptors.request.use(
    config => {    
        let token = window.localStorage.getItem('token');
        console.log("每次请求前读取 Token=" + token)
        if (token) {
            config.headers.Authorization = "Bearer " + token;
        }
		return config;
    },
    error => {
        return Promise.reject(error);
    }
);
//响应拦截
instance.interceptors.response.use(
	//第一个参数是一个匿名函数作为参数变量，正常响应 HTTP 状态码 200
	response => {
		console.log("正常响应 HTTP 状态码:"+response.status);
		//resp.data.code！ = 200
		return response;
	},
	//第二个参数是一个匿名函数,出错了非正常响应
	error => {
		if(error.response){//如果springboot 没有启动，就没有这个
			switch(error.response.status){
				case 401:
				Message.error("401无权限……");
				//可清除token
				break;
				case 403:
				Message.error("403 无授权……");
				break;
				default:
				Message.error(error.response.status+"系统在建设……");
				break;
			}
		}
		return Promise.reject(error.response);//继续往下执行
	}
)


export let $get = (url,obj)=>{
	return instance.get(url,{params:obj})
}


export let $postKv = (url,obj)=>{
	
	var head ={"headers":{
	 'Content-Type':'application/x-www-form-urlencoded;charset=utf8'},
	 };
	console.log(head);
	let kv = qs.stringify(obj);//转键值对
	console.log(kv);
	return instance.post(url,
	kv,
	head)
};



export let $postj = (url,obj)=>{
	return instance.post(url,obj,{headers:{'Content-Type':'application/json;charset=utf8'}})
};

export let $postf = (url,formdata)=>{
	
	var head ={"headers":{
						'Content-Type':'multipart/form-data'},
						};
	console.log(head);
	return instance.post(url,formdata,{headers:{'Content-Type':'multipart/form-data'}})
}